<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>查看及编辑决策树配置</title>
        <script src="/lib/axios.js"></script>
        <script src="/lib/vue.js"></script>
        <link rel="stylesheet" href="/lib/elementindex.css">
        <script src="/lib/elementindex.js"></script>
        <style>
            .el-dialog__body{
                padding-top: 0px;
            }
            .el-table td
            {
                padding-top: 2px;
                padding-bottom: 2px;
            }
        </style>
    </head>
    <body>
        <div id="app" style="width:100%">
            <el-tabs value='config'>
                <el-tab-pane label="基本信息" name="rbasic">
                    <hc-rule-basic :ruledef='ruleDef'></hc-rule-basic>
                </el-tab-pane>
                <el-tab-pane label="规则配置" name="config">
                    <el-form ref="form" label-width="auto">
                        <el-form-item label="">
                            <el-dropdown size='medium' split-button type="primary" :hide-on-click="false" @command="handleAppendAction">
                                添加行动列
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item v-for="(actiondef,code) in hc$action$registry" :command='code'
                                        :key="code">{{actiondef.name}}</el-dropdown-item>
                                </el-dropdown-menu>
                        </el-form-item>
                        <el-table :indent="32" :data="[ruleDef.root]" style="width: 100%;margin-bottom: 20px;"
                            :span-method="onMergeVariableColumn" row-key="id" border default-expand-all :tree-props="{children: 'list', hasChildren: 'hasChildren'}">
                            <el-table-column label="决策条件" min-width="80%">
                                <template slot-scope="scope">
                                    <span>{{scope.row.id +':' + scope.row.referName +(scope.row.rname?':'+scope.row.rname:'')}}</span>
                                    <el-link v-if="scope.row.rpath == null" type="primary" @click='handleAddClass9Event(scope.row)'>添加</el-link>
                                    <el-link v-else type="danger" @click='handleDeleteClass9Event(scope.row)'>移除</el-link>
                                </template>
                            </el-table-column>

                            <el-table-column v-for="(col,index) in ruleDef.actionDefList" :key="col.id">
                                <template slot="header">
                                    <span>{{col.name}}</span>
                                    <el-link type="primary" @click="handleActionSetting({col:col,index:index})">设置
                                    </el-link>
                                </template>

                                <template slot-scope="scope">
                                    <component v-if="scope.row.rpath == null && hc$action$registry[col.type]" v-bind:is="hc$action$registry[col.type].input"
                                        v-model='scope.row.valueMap[col.code]' v-bind:refer='col.refer' v-bind:definition='col'></component>
                                    <span v-else></span>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-form-item label="">
                            <el-button type="primary" @click='handleUpdateRuleEvent'>保存修改</el-button>
                            &nbsp;&nbsp;
                            <el-button type="danger" @click='handleDeleteRuleEvent'>删除规则</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="规则测试" name="test">
                    <hc-test :rpath="ruleDef.rpath" :inputs='ruleDef.rtest' @save-inputs="ruleDef.rtest = $event"></hc-test>
                </el-tab-pane>
            </el-tabs>
        </div>

        <div id='settingdlg'>
            <el-dialog :data='setting' :visible.sync="visible" title="决策行动设置">
                <el-form :model='setting' ref="settingform" label-width="80px">
                    <el-tabs value='setting'>
                        <el-tab-pane label="基本设置" name="setting">
                            <el-form-item label="行动代码" prop='code' :rules="[{
                    				required: true,
                    				message: '请输入行动代码',
                    				trigger: 'blur'
                    			},
                    			{
                    				min: 3,
                    				max: 30,
                    				message: '长度在 3 到 30 个字符',
                    				trigger: 'blur'
                    			}
                    		]">
                                <el-input v-model="setting.code" placeholder="请输入行动代码" onkeyup="value=$util.tokentrim(value)"
                                    onbeforepaste="clipboardData.setData('text',$util.tokentrim(clipboardData.getData('text')))"></el-input>
                            </el-form-item>

                            <el-form-item label="行动说明" prop='name'>
                                <el-input v-model.trim="setting.name" placeholder="输入行动说明"></el-input>
                            </el-form-item>

                            <el-form-item label="动作类型" prop='type' :rules="[{
                    				required: true,
                    				message: '请选择动作类型',
                    				trigger: 'blur'
                    			}
                    		]">
                                <el-select disabled style='width: 100%;' v-model="setting.type" placeholder="请选择">
                                    <el-option v-for="item in hc$action$registry" :value='item.code' :label='item.name'
                                        :key="item.code">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            
                            <component v-if='hc$action$registry[setting.type]' v-bind:is="hc$action$registry[setting.type].refer"
                                v-bind:definition='setting'></component>
                        </el-tab-pane>
                        
                        <el-tab-pane label="结果映射" name="mapping">
                            <el-table :indent="20" :data="setting.resultStruct?[setting.resultStruct]:[]" style="width: 100%;margin-bottom: 20px;"
                                row-key="id" border default-expand-all :tree-props="{children: 'list', hasChildren: 'hasChildren'}"
                                empty-text='请先完成基本设置' :default-sort="{prop: 'important', order: 'descending'}">
                                <el-table-column label="结果名称" prop="name" sortable>
                                    <template slot-scope="scope">
                                        <span v-if='scope.row.important>10'>*&nbsp</span><span>{{scope.row.name }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="映射到变量" prop="variableId">
                                    <template slot-scope="scope">
                                        <el-cascader style='width: 100%;' :change-on-select='true' :props="{label:'label',value:'id',children:'list',expandTrigger:'hover',emitPath:false}"
                                            v-model='setting.resultMap[scope.row.id]' placeholder="关键字搜索" :options="variableList"
                                            filterable clearable>
                                        </el-cascader>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>

                    </el-tabs>

                    <el-form-item>
                        <el-button @click='handleSettingSubmit' type="primary">确认</el-button>
                        <el-button type='danger' v-if='setting.id > 0' @click='handleSettingDelete'>删除</el-button>
                        <el-button v-if='setting.id==0' @click='visible=false'>取消</el-button>
                    </el-form-item>

                </el-form>
            </el-dialog>
        </div>

        <script src="/lib/ace-noconflict/ace.js"></script>
        <!-- <script src="/lib/ace-noconflict/ext-language_tools.js"></script> -->
        <link rel="stylesheet" href="/com/hc-groovy-editor.css" />
        <link rel="stylesheet" href="/com/hc-lang-editor.css" />
        <script type='module'>
            import * as $util from '/lib/hc-util.js'
            import * as $rest from '/lib/hc-rest-service.js'
            import {} from '/com/hc-test.js'
            import {} from '/com/hc-rule-basic-properties.js'
            // import {} from '/com/hc-groovy-editor.js'
            
            import hc$action$registry from './hc-action-com-registry.js'
            import HcRuleClass9Dialog from '/com/hc-rule-class9-dialog.js'

            function onDeleteClass9Event(class9row) {
                console.log(class9row)
                class9row.rpath = null;
                class9row.rname = "";
                class9row.list.splice(0, class9row.list.length);
            }

            let rpath = $util.getUrlArgOrDefault('rpath', 'xsxdjc/SimpleTree')
            $rest.check$pinfoOrLoad(
                function() {
                    $rest.obtainRuleDefByRpath(rpath, initvm);
                }, 'xsxdjc/Main');

            function initvm(ruleDef) {
                let variableList = $pinfo.ruleList.find(it => it.rtype == 'variable').list;
                $util.$tree.enlabel(variableList);

                window.vmdlg = new Vue({
                    el: '#settingdlg',
                    data: {
                        setting: {},
                        visible: false,
                        variableList: variableList,
                        hc$action$registry: hc$action$registry,
                    },
                    methods: {
                        handleSettingSubmit: function() {
                            let self = this;
                            this.$refs['settingform'].validate((valid) => {
                                if (valid) {
                                    if (!this.setting.id) this.actionAppend()
                                    else this.actionUpdate();
                                    this.visible = false
                                } else {
                                    self.$message({
                                        type: 'warning',
                                        message: '验证失败，请检查行动设置 和 结果映射.'
                                    })
                                    return false;
                                }
                            });
                        },
                        handleSettingDelete: function() {
                            this.actionDelete()
                            this.visible = false
                        },
                        actionAppend: function() {
                            this.setting.id = vm.ruleDef.actionmaxid;
                            vm.ruleDef.actionDefList.push(this.setting);
                        },
                        actionUpdate: function() {},
                        actionDelete: function() {
                            let index = vm.ruleDef.actionDefList.findIndex(it => it.id === this.setting.id);

                            deleteColumn(vm.ruleDef.root, index);

                            vm.ruleDef.actionDefList.splice(index, 1);

                            function deleteColumn(root, index) {
                                root.actionList.splice(index, 1);
                                if(root.list)
                                {
                                    root.list.forEach(
                                        element =>
                                        deleteColumn(element, index));
                                 };
                            };
                        },
                    },
                });
                
                window.vm = new Vue({
                    el: '#app',
                    data: {
                        ruleDef: ruleDef,
                        hc$action$registry: hc$action$registry,
                    },
                    methods: {
                        handleUpdateRuleEvent: function() {
                            this.ruleDef.actionDefList.forEach(def=>{
                                for(let dataId in def.resultMap)
                                {
                                    if(!def.resultMap[dataId]) delete def.resultMap[dataId];
                                };
                            });
                            //,function(ruleDef){document.location.reload(true);}
                            $rest.updateRuleDefInVm(this,function(ruleDef){document.location.reload(true);});
                        },
                        handleDeleteRuleEvent: function() {
                            $rest.deleteRuleDefInVm(this)
                        },
                        handleAddClass9Event: function(class9row) {
                            currentBranchRow = class9row;
                            class9SelectDlg.show()
                        },
                        handleDeleteClass9Event: function(class9row) {
                            class9row.rpath = null;
                            class9row.rname = "";
                            class9row.list.splice(0, class9row.list.length);
                        },

                        handleAppendAction: function(cmd) {
                            let id = ++vm.ruleDef.actionmaxid
                            vmdlg.setting = {
                                id: 0, //0 is appending flag
                                code: '行动' + id,
                                name: '行动' + id,
                                type: cmd,
                                refer: null,
                                resultMap:{}
                            };
                            vmdlg.visible = true;
                        },
                        handleActionSetting: function(colInfo) {
                            vmdlg.setting = colInfo.col;
                            vmdlg.visible = true;
                        },
                        onMergeVariableColumn: onMergeVariableColumn
                    }
                });
                
                window.class9SelectDlg = new HcRuleClass9Dialog({
                    ruledefinition: true,
                    class9selected: function(class9Def) {
                        currentBranchRow.rpath = class9Def.rpath;
                        currentBranchRow.rname = class9Def.rname;

                        if (!currentBranchRow.list) currentBranchRow.list = [];

                        class9Def.list.forEach(ele => {
                            currentBranchRow.list.push({
                                id: ++vm.ruleDef.rmaxid,
                                referId:ele.id,
                                referName: ele.code,//ele.name ? ele.code + '-' + ele.name : ele.code,
                                rpath: null,
                                rname: "",
                                list: [],
                                valueMap:{},
                            });
                        });
                    }
            });

            };

            var currentBranchRow
            
            function onMergeVariableColumn({
                row,
                column,
                rowIndex,
                columnIndex
            }) {
                let actionCount = vm.ruleDef.actionDefList.length;
                let colspan = row.rpath ? actionCount + 1 : 1;
                return {
                    rowspan: 1,
                    colspan: colspan
                }
            }
        </script>

    </body>

</html>
